#!/bin/bash
#
# confProxyFirefox This shell script takes care of starting and stopping
# confProxyFirefox daemon.
#
# chkconfig: 2345 56 10
# description: configure wpad script on firefox
#
### BEGIN INIT INFO
# Provides: firefox configuration on wpad scripting
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 2 3 4 5
# License: GPL
# Version: 0.1
# Short-Description: Configure script proxy for local network
# Description: Modify user preferences configuration over proxy
# adding script wpad and change configuration proxies
# to access the internet. Optized to RedHat linux variation
### END INIT INFO

function _help(){
echo "# Autor: Ricardo Brito do Nascimento"
echo "# E-mail: ricardo[at]rbncurriculo.cjb.net"
echo "# Data: 10/11/2007"
echo
echo "# Versão: 0.1"
echo "# Licença: GPL"
echo "# Script: confProxyFirefox.sh"
echo "# Funcao: Executa a configuração do firefox para utilização"
echo "# de script de proxy para navegadores, em todos os"
echo "# usuários do sistema;"
echo "# Descrição: Modifica a preferencia de usuário para configuração do proxy"
echo "# acrescentando o script e mudando a configuração do proxy para"
echo "# acesso a internet. Otimizado para distribuições com variação RedHat."
echo "# Configuração: Configure as váriaveis HOMEUSER e SCRIPTPROXY com os valores"
echo "# reais desejados."
echo -e "\nUse: $0 {set | start | stop | unset | status}\n"
}

HOMEUSER=/home
SCRIPTPROXY=http://localhost/script/wpad.dat
PROXYADDRESS=http://10.1.101.101
PROXYPORT=8080

# Source function library.
. /etc/init.d/functions

#Logado como root
if [ `whoami` != "root" ]; then
echo -e "\nPara executar este script deve ter status\n de Super Usuário ou ser executar como 'root'\n\n";
exit 1;
fi

function _setProxy(){

find $HOMEUSER/*/.mozilla/firefox/*/prefs.js| while read a;
do
echo -n 'user_pref("network.proxy.autoconfig_url", "'$SCRIPTPROXY'");' >> $a && success || failure;
echo -n 'user_pref("network.proxy.type", 2);' >> $a&& success || failure;
echo $a;
done
}

function _unsetProxy(){
find $HOMEUSER/*/.mozilla/firefox/*/prefs.js| while read a;
do
grep -vi network.proxy $a > /tmp/prefs.js && success || failure;
cp -f /tmp/prefs.js $a;
echo $a
done
}

function _status(){
rm -f /tmp/{file,count} 2> /dev/null

find $HOMEUSER/*/.mozilla/firefox/*/prefs.js| while read a;
do
let file++;
echo $file > /tmp/file 2> /dev/null
done

grep -i network.proxy $HOMEUSER/*/.mozilla/firefox/*/prefs.js | while read a;
do
let COUNT++;
echo $COUNT > /tmp/count;
#echo $COUNT
done
if [ ! -e /tmp/count ];then
echo 0 > /tmp/count;
fi
NUM=$(expr `cat /tmp/count`)

echo "$(cat /tmp/file 2> /dev/null) conta(s) e $NUM com o scrpt proxy ativo."
}

case $1 in
start|set) _setProxy ;;
stop|unset) _unsetProxy ;;
st|stat|status) _status ;;
?|-h|--help) _help;;
*) 
printf $"Use: $0 {set | start | stop | unset | status | ? | -h | --help}\n"
exit 1
esac
